package bom.example.common.exportword;

import bom.example.common.utils.PathUtils;
import cn.afterturn.easypoi.word.WordExportUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.util.Assert;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author X.I.O
 * @title: WordUtils
 * @projectName springboot
 * @description: TODO
 * @date 2021/10/31 14:12
 */
public class WordUtils {

    /**
     * 生成word
     * @param templatePath
     * @param temDir
     * @param fileName
     * @param params
     */
    public static void exportWord(String templatePath, String temDir, String fileName, Map<String,Object> params){
        Assert.notNull(templatePath, "模板路径不能为空");
        Assert.notNull(temDir, "临时文件路径不能为空");
        Assert.notNull(fileName, "导出文件名不能为空");
        Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");
        if (!temDir.endsWith("/")) {
            temDir = temDir + File.separator;
        }
        File dir = new File(temDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
            String tmpPath = temDir + fileName;
            FileOutputStream fos = new FileOutputStream(tmpPath);
            doc.write(fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String path= PathUtils.getPath();
        String donload=path+File.separator+"donload";
        path=path+File.separator+"muban"+File.separator+"模板.docx";
        File file=new File(path);
        Map<String,Object> map = new HashMap<>();
        map.put("code","100");
        map.put("username", "张三");
        map.put("company","xx公司" );
        map.put("date","2020-04-20" );
        map.put("dept","IT部" );
        map.put("startTime","2020-04-2008:00:00" );
        map.put("endTime","2020-04-2008:00:00" );
        map.put("reason", "外出办公");
        map.put("time","2020-04-22" );
        exportWord(path,donload ,"生成文件.docx" ,map );
    }
}
